package bbs;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import util.DB;

public class BoardDAO {

    private static Board makeBoard(ResultSet rs) throws Exception {
        Board obj = new Board();
        obj.setId(rs.getInt("Id"));
        obj.setTitle(rs.getString("title"));
        obj.setCommentEnabled(rs.getBoolean("commentEnabled"));
        obj.setFileAttachEnabled(rs.getBoolean("fileAttachEnabled"));
        obj.setGuestReadAllowed(rs.getBoolean("guestReadAllowed"));
        return obj;
    }

    public static Board selectById(int id) throws Exception {
        String sql = "SELECT * FROM bbs.[Board] WHERE [id] = ?";
        try (Connection con = DB.getConnection();
             PreparedStatement stmt = con.prepareStatement(sql)) {
            stmt.setInt(1, id);
            ResultSet rs = stmt.executeQuery();
            return rs.next()? makeBoard(rs) : null;
        }
    }

    public static void updateTitle(int boardId, String title) throws Exception {
        String sql = "UPDATE bbs.[Board] SET [title]=? WHERE [id]=?";
        try (Connection con = DB.getConnection();
             PreparedStatement stmt = con.prepareStatement(sql)) {
            stmt.setString(1, title);
            stmt.setInt(2, boardId);
            stmt.executeUpdate();
        }
    }

}